<template>
    <div class="materialMgt-index yuan-container">
        <a-card title="物料管理">
            <div style="padding: 20px">
                <h2>物料/产品添加顺序</h2>
                <a-steps progress-dot :current="5">
                    <a-step title="添加物料：中药材" sub-title="步骤一"/>
                    <a-step title="添加物料：半成品提取饮片" sub-title="步骤二"/>
                    <a-step title="添加物料：半成品提取物" sub-title="步骤三"/>
                    <a-step title="添加物料：待包装成品颗粒" sub-title="步骤四"/>
                    <a-step title="添加物料：成品颗粒" sub-title="步骤五"/>
                </a-steps>
            </div>
            <a-tabs type="card" :default-active-key="rawTypeKey" @change="tabChange">
                <a-tab-pane v-for="(item, i) in tabsData" :key="item.rawType" :tab="item.name"></a-tab-pane>
            </a-tabs>

            <div class="filter-panel">
               <a-input-search class="filter-list" allowClear v-model="keywords" placeholder="请输入品名/入库批号" @search="resetList" />
                <div class="filter-list" style="float: right;margin-right: 0">
                    <a-button id="新增" type="primary" @click="add">新增</a-button>
                    <a-button v-if="this.rawTypeKey !='其他'" type="primary" @click="downloadTpl">下载导入模板</a-button>
                    <a-upload v-if="this.rawTypeKey !='其他'" name="file" :multiple="false" :beforeUpload="beforeUpload" :showUploadList="false">
                        <a-button type="primary" style="margin-left: 5px;margin-right: 0">导入</a-button>
                    </a-upload>
                </div>
            </div>
            <div class="table">
                <a-table bordered :rowKey="item=>item.id" :data-source="pageList" :columns="columns" :pagination="pagination" :loading="loading"></a-table>
            </div>
        </a-card>

        <add-or-edit :viewDetail="viewDetail" :editId="editId" :rowKey="rawTypeKey" :visible="addVisible" @closeModal="closeModal"/>

    </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { h } from "vue";
import config from "@/utils/config";
import addOrEdit from "@/views/settingView/materialMgt/components/addOrEdit.vue";
import { downLoadFile } from "@/utils";
import nextApi from "@/api/nextApi";
import { driver } from "driver.js";// 引入driver.js
import "driver.js/dist/driver.css";// 引入driver.js的样式
@Component({
    name: "materialMgtMgtIndex",
    components: {addOrEdit },
})
export default class extends Vue {
    tabsData = config.tabsData;
    pagination = {
        pageSize: 10,
        current: 1,
        total: 0,
        showTotal: (total: number) => `共${total}条`,
        onChange: this.pageChange,
    };
    columns = [
        {
            title: "序号",
            dataIndex: "index",
            key: "index",
            align: "center",
            customRender: (text: any, record: any, index: any) => `${index + 1}`,
        },
        {
            align: "center",
            dataIndex: "name",
            key: "name",
            title: "物料名称",
        },
        {
            align: "center",
            dataIndex: "category",
            key: "category",
            title: "物料类型",
            customRender: (text: any, record: any, index: any) => this.getRawTypeName(),
        },
        // {
        //     align: "center",
        //     dataIndex: "standard",
        //     key: "standard",
        //     title: "标准"
        // },
        {
            align: "center",
            dataIndex: "code",
            key: "code",
            title: "物料代码",
        },
        {
            align: "center",
            dataIndex: "state",
            key: "state",
            title: "状态",
            customRender: (text: string, record: any, index: number) => {
                const stateBox = h(
                    "div",
                    { class: record.state === true ? "c-success" : "c-danger" },
                    record.state === true ? "启用" : "禁用"
                );
                return stateBox;
            },
        },
        {
            align: "center",
            dataIndex: "action",
            key: "action",
            title: "操作",
            width: 260,
            customRender: (text: any, record: any) => {
                const statusDom = h(
                    "a-popconfirm",
                    {
                        props: {
                            title: record.state === true ? "确定要禁用吗？" : "确定要启用吗？",
                            okText: "确定",
                            cancelText: "取消",
                        },
                        on: { confirm: () => this.clickDisable(record) },
                    },
                    [
                        h(
                            "a-button",
                            {
                                style: { marginRight: "5px" },
                                props: { icon: "tool", type: record.state === true ? "danger" : "primary", size: "small" },
                            },
                            record.state === true ? "禁用" : "启用"
                        ),
                    ]
                );

                const editBtn = h(
                    "a-button",
                    {
                        style: { marginRight: "5px" },
                        props: { icon: "edit", type: "primary", size: "small" },
                        on: { click: () => this.editDetail(record) },
                    },
                    "编辑"
                );
                const detailBtn = h(
                    "a-button",
                    {
                        style: { marginRight: "10px" },
                        props: { icon: "eye", type: "primary", size: "small" },
                        on: { click: () => this.showDetail(record) },
                    },
                    "详情"
                );

                const btn: any[] = [];
                btn.push(editBtn);
                btn.push(detailBtn);
                btn.push(statusDom);
                return h("div", btn);
            },
        },

    ];
    loading = false;
    pageList: any[] = [];
    keywords = "";
    rawTypeKey = "中药材";


    async mounted() {
        await this.getList();
        const driverEnabled = localStorage.getItem("driver-enabled");
        let status = false;

        if (driverEnabled !== null) {
            try {
                status = JSON.parse(driverEnabled);
            } catch (error) {
                console.error("Error parsing driver-enabled from localStorage:", error);
                status = false; // 如果解析失败，默认设置为 false
            }
        }
        if (status) {
            this.startStep();
            localStorage.setItem("fromMaterialPage",'true')
        }
    }
    driver:any = null
    steps:any = [
        {
            element: ".ant-tabs-tab-active",
            popover: {
                title: "物料/产品添加顺序-步骤一",
                description: "添加物料需要先添加中药材",
                side: "right",
                nextBtnText: "下一步",
                prevBtnText: "上一步",
            },
        },
        {
            element: "#新增",
            popover: {
                title: "物料/产品添加顺序-步骤二",
                description: "点击新增按钮填写所需要的数据",
                side: "right",
                nextBtnText: "下一步",
                prevBtnText: "上一步",
            },
        },
        {
            element: ".ant-menu-item.产品管理",
            popover: {
                title: "物料/产品添加顺序-步骤三",
                description: "点击产品管理跳转到产品管理页面",
                side: "right",
                nextBtnText: "下一步",
                prevBtnText: "上一步",
                onNextClick: () => {
                    this.$router.push({ path: "/productMgt" });
                },
            },
        },
    ]
    startStep(){
        this.driver = driver({
            showButtons: ["next", "previous", "close"],// 是否显示按钮
            showProgress: false, // 是否显示步骤进度
            steps: this.steps, // 步骤列表
            allowClose: true, // 是否点击蒙层进行关闭
            //点击关闭
            onDestroyStarted: () => {
                this.driver.destroy();
                localStorage.setItem("driver-enabled", "false");
            },
        });
        this.driver.drive()
    }
    async getList() {
        this.pageList = [];
        try {
            this.loading = true;
            const res = await nextApi.getMaterialList({
                pageSize: this.pagination.pageSize,
                page: this.pagination.current,
                name: this.keywords,
                materialType: this.rawTypeKey,
            });
            this.pagination.total = res.data?.total || 0;
            this.pageList = res.data?.records || [];
        } finally {
            this.loading = false;
        }
    }
    resetList() {
        this.pagination.current = 1;
        this.getList();
    }
    tabChange(e: string) {
        this.rawTypeKey = e;
        this.resetList();
    }
    getRawTypeName() {
        const find = this.tabsData.find((item) => item.rawType === this.rawTypeKey);
        return find ? find.name : "--";
    }
    pageChange(page: number, pageSize: number) {
        this.pagination.pageSize = pageSize;
        this.pagination.current = page;
        this.getList();
    }
    viewDetail = false;
    showDetail(item: any) {
        this.editId = item.id;
        this.addVisible = true;
        this.viewDetail = true;
    }

    editId = "";
    addVisible = false;
    editDetail(item: any) {
        this.editId = item.id;
        this.addVisible = true;
    }
    add() {
        this.editId = "";
        this.addVisible = true;
    }
    closeModal(){
        this.addVisible = false;
        this.viewDetail = false;
        this.editId = "";
        this.getList();
    }
    downloadTpl() {
        this.loading = true;
        nextApi.downloadMaterialTpl({ materialType: this.getRawTypeName() }, (res: any) => {
            const blob = new Blob([res.data], {
                //type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                type: "application/vnd.ms-excel",
            });
            downLoadFile(blob, this.getRawTypeName() + "_导入模板");
            this.loading = false;
        });
    }
    beforeUpload(file: any) {
        let formData = new FormData();
        formData.append("file", file);
        formData.append("materialType", this.rawTypeKey);
        this.uploadAccount(formData);
        return false;
    }
    async uploadAccount(formData: any) {
        this.loading = true;
        try {
            const res = await nextApi.importMPData(formData);
            console.log(res)
            this.$message.success(res.msg);
            await this.getList()
        } finally {
            this.loading = false;
        }
    }
    async clickDisable(item:any){
        try{
            this.loading = true
            let {state,id} = item
            const res = await nextApi.changeState({id,state:!state})
            this.$message.success(res.msg)
        }finally {
            this.loading = false
            await this.getList()
        }

    }
}
</script>
<style scoped lang="scss">
.materialMgt-index {
    padding: 20px;
}

</style>
